<html lang="en-US">

<head>
    
<title>生产环境遇到一个 Go 问题，整组人都懵逼了... - 花落雨忧</title>

<meta property="og:title" content="生产环境遇到一个 Go 问题，整组人都懵逼了... - 花落雨忧">



    



    
    <meta property="description" content="大家好，我是煎鱼。
前段时间正在疯狂写代码的时候，突然有一个读者给我提了一个问题，让我有了一定的兴趣：
我还是比较感兴趣的，因为是生产环境、有代码，且整组人都懵逼的问题。
在征求了小伙伴的意见后，今天分享出来，大家也思考一下原因，一起规避这个 “坑”。
[&amp;hellip;] 代码示例如下：
[&amp;hellip;] type MyErr struct { Msg string } func &amp;hellip;">
    <meta property="og:description" content="大家好，我是煎鱼。
前段时间正在疯狂写代码的时候，突然有一个读者给我提了一个问题，让我有了一定的兴趣：
我还是比较感兴趣的，因为是生产环境、有代码，且整组人都懵逼的问题。
在征求了小伙伴的意见后，今天分享出来，大家也思考一下原因，一起规避这个 “坑”。
[&amp;hellip;] 代码示例如下：
[&amp;hellip;] type MyErr struct { Msg string } func &amp;hellip;">
    






<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">

<link rel="shortcut icon" href="https://www.lican.site/logo/logo.png" type="image/x-icon" />



<link rel="stylesheet" href="/css/style.min.css" />

<link rel="stylesheet" href="/css/reset.min.css" />




<script src="https://www.lican.site/js/highlight.min.js"></script>

<script>
hljs.configure({ ignoreUnescapedHTML: true })
hljs.highlightAll();
</script>


<script src="https://www.lican.site/js/jquery.min.js"></script>




<link href="https://www.lican.site/css/hugo-code.min.css" rel="stylesheet" />



    <style>
        .post-content img {
            max-width: 400px;
        }
    </style>
</head>

<body id="period" class="home blog">
    <a class="skip-content" href="#main">Press "Enter" to skip to content</a>
    <div id="overflow-container" class="overflow-container">
        <header class="site-header" id="site-header" role="banner">
    <div class="max-width">
        <div id="title-container" class="title-container">
            <div id="site-title" class="site-title"><a href="/">花落雨忧</a></div>
            <p class="tagline">思所及 力所行 方为真.</p>
        </div>
        
        <div id="menu-primary-container" class="menu-primary-container">
            <div class="icon-container">
            </div>
            <div id="menu-primary" class="menu-container menu-primary" role="navigation">
                <nav class="menu">
                    <ul id="menu-primary-items" class="menu-primary-items">
                        
                        
                        <li id="menu-item-0"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/posts" aria-current="page" tabindex="0">首页</a></li>
                        
                        <li id="menu-item-1"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/tech/" aria-current="page" tabindex="1">技术文档</a></li>
                        
                        <li id="menu-item-2"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/article/" aria-current="page" tabindex="2">文章</a></li>
                        
                        <li id="menu-item-3"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/project/" aria-current="page" tabindex="3">项目</a></li>
                        
                        <li id="menu-item-4"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/about/" aria-current="page" tabindex="4">关于</a></li>
                        
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</header>
        <div id="primary-container" class="primary-container">
            <div class="max-width">
                <section id="main" class="main" role="main">
                    <div id="loop-container" class="loop-container">
                        <div
                            class="post type-post status-publish format-standard hentry entry">
                            <article>
                                <div class="post-container">
                                    <div class="post-header">
                                        <h2 class="post-title">
                                            <a href="/posts/go/go-errors-boom/">生产环境遇到一个 Go 问题，整组人都懵逼了...</a>
                                        </h2>
                                        
                                        <div class="post-byline">Published on
                                            <a class="date" href="javascript:;">2021/07/07</a>
                                            
                                            
                                            
                                            
                                            
                                        
                                    </div>
                                    <div class="post-content">
                                        <p>大家好，我是煎鱼。</p>
<p>前段时间正在疯狂写代码的时候，突然有一个读者给我提了一个问题，让我有了一定的兴趣：</p>
<p><img src="https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/c1011e66fe104d228dcaa2083b554fc8~tplv-k3u1fbpfcp-watermark.image" alt="image.png"></p>
<p>我还是比较感兴趣的，因为是生产环境、有代码，且整组人都懵逼的问题。</p>
<p>在征求了小伙伴的意见后，今天分享出来，大家也思考一下原因，一起规避这个 “坑”。</p>
<h2 id="案例一">案例一</h2>
<p>代码示例如下：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-golang" data-lang="golang"><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">MyErr</span> <span style="color:#66d9ef">struct</span> {
    <span style="color:#a6e22e">Msg</span> <span style="color:#66d9ef">string</span>
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">main</span>() {
    <span style="color:#66d9ef">var</span> <span style="color:#a6e22e">e</span> <span style="color:#66d9ef">error</span>
    <span style="color:#a6e22e">e</span> = <span style="color:#a6e22e">GetErr</span>()
    <span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#a6e22e">e</span> <span style="color:#f92672">==</span> <span style="color:#66d9ef">nil</span>)
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">GetErr</span>() <span style="color:#f92672">*</span><span style="color:#a6e22e">MyErr</span> {
    <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">nil</span>
}

<span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">m</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">MyErr</span>) <span style="color:#a6e22e">Error</span>() <span style="color:#66d9ef">string</span> {
    <span style="color:#66d9ef">return</span> <span style="color:#e6db74">&#34;脑子进煎鱼了&#34;</span>
}
</code></pre></div><p>请思考一下，<strong>这段程序的输出结果是什么</strong>？</p>
<p>该程序所调用的 <code>GetErr</code> 方法所返回的是 <code>nil</code>，而外部判断是 <code>e == nil</code>，因此最终的输出结果是 true，对吗？</p>
<p>输出结果如下：</p>
<pre><code>2021/04/04 08:39:04 false
</code></pre><p>答案是：false。</p>
<h2 id="案例二">案例二</h2>
<p>代码示例如下：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-golang" data-lang="golang"><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">Base</span> <span style="color:#66d9ef">interface</span> {
    <span style="color:#a6e22e">do</span>()
}

<span style="color:#66d9ef">type</span> <span style="color:#a6e22e">App</span> <span style="color:#66d9ef">struct</span> {
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">main</span>() {
    <span style="color:#66d9ef">var</span> <span style="color:#a6e22e">base</span> <span style="color:#a6e22e">Base</span>
    <span style="color:#a6e22e">base</span> = <span style="color:#a6e22e">GetApp</span>()
    
    <span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#a6e22e">base</span>)
    <span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#a6e22e">base</span> <span style="color:#f92672">==</span> <span style="color:#66d9ef">nil</span>)
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">GetApp</span>() <span style="color:#f92672">*</span><span style="color:#a6e22e">App</span> {
    <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">nil</span>
}
<span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">a</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">App</span>) <span style="color:#a6e22e">do</span>() {}
</code></pre></div><p>请思考一下，<strong>这段程序的输出结果是什么</strong>？</p>
<p>该程序调用了 <code>GetApp</code> 方法，该方法返回的是 <code>nil</code>，因此其赋值的 <code>base</code> 也是 <code>nil</code>。因此判断 <code>base == nil</code> 的最终输出结果是 <code>&lt;nil&gt;</code> 和 <code>true</code>，对吗？</p>
<p>输出结果如下：</p>
<pre><code>2021/04/04 08:59:00 &lt;nil&gt;
2021/04/04 08:59:00 false
</code></pre><p>答案是：<code>&lt;nil&gt;</code> 和 false。</p>
<h2 id="为什么">为什么</h2>
<p>为什么，这两段 Go 程序是怎么回事&hellip;也太反直觉了？其背后的原因本质上还是对 Go 语言中 interface 的基本原理的理解。</p>
<p>在案例一中，虽然 <code>GetErr</code> 方法确实是返回了 <code>nil</code>，返回的类型也是具体的 <code>*MyErr</code> 类型。但是其接收的变量却不是具体的结构类型，而是 <code>error</code> 类型：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-golang" data-lang="golang"><span style="color:#66d9ef">var</span> <span style="color:#a6e22e">e</span> <span style="color:#66d9ef">error</span>
<span style="color:#a6e22e">e</span> = <span style="color:#a6e22e">GetErr</span>()
</code></pre></div><p>在 Go 语言中， <code>error</code> 类型本质上是 interface：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-golang" data-lang="golang"><span style="color:#66d9ef">type</span> <span style="color:#66d9ef">error</span> <span style="color:#66d9ef">interface</span> {
    <span style="color:#a6e22e">Error</span>() <span style="color:#66d9ef">string</span>
}
</code></pre></div><p>因此兜兜转转又回到了 interface 类型的问题，interface 不是单纯的值，而是<strong>分为类型和值</strong>。</p>
<p>所以传统认知的此 nil 并非彼 nil，<strong>必须得类型和值同时都为 nil 的情况下，interface 的 nil 判断才会为 true</strong>。</p>
<p>在案例一中，结合代码逻辑，更符合场景的是：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-golang" data-lang="golang"><span style="color:#66d9ef">var</span> <span style="color:#a6e22e">e</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">MyErr</span>
<span style="color:#a6e22e">e</span> = <span style="color:#a6e22e">GetErr</span>()
<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#a6e22e">e</span> <span style="color:#f92672">==</span> <span style="color:#66d9ef">nil</span>)
</code></pre></div><p>输出结果就会是 true。</p>
<p>在案例二中，也是一样的结果，原因也是 interface。不管是 <code>error</code> 接口（interface），还是自定义的接口，背后原理一致，自然也就结果一致了。</p>
<h2 id="总结">总结</h2>
<p>今天这篇文章，相当于是《Go 面试题：Go interface 的一个 “坑” 及原理分析》的变形了，毕竟是生产环境的代码改造而来，更贴合真实的实际场景。</p>
<p>下意识的直觉有时候不是绝对正确的，我们要正确的理解 Go 语言中的那些知识点，才能更好地实现早下班的理想和愿景。</p>


                                        
                                        
                                        
                                        <div class="rp4wp-related-posts">
                                            <h3>相关文章</h3>
                                            <ul>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/gmp-why-p/">经典面试题：你觉得 Go 在什么时候会抢占 P？</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/go-empty-struct/">用 Go struct 不能犯的一个低级错误！</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/go-bootstrap0/">详解 Go 程序的启动流程，你知道 g0，m0 是什么吗？</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/goroutine-leak/">跟面试官聊 Goroutine 泄露的 6 种方法，真刺激！</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/struct-pointer/">你知道 Go 结构体和结构体指针调用有什么区别吗？</a>
                                                    </div>
                                                </li>
                                                
                                            </ul>
                                        </div>
                                        
                                        
                                    </div>

                                    
                                    
                                    

                                    
                                    <div class="post-meta">
                                        
                                        
                                        <div class="post-tags">
                                            <ul>
                                            
                                            <li>
                                                <a href="/tags/go" title="View all posts tagged match">go</a>
                                            </li>
                                            
                                            </ul>
                                        </div>
                                        
                                        
                                        <nav class="further-reading">
                                            
                                            <div class="previous">
                                                <span>&lt;&lt; Prev</span>
                                                <a href="https://www.lican.site/posts/go/gmp-why-p/"
                                                    rel="prev">经典面试题：你觉得 Go 在什么时候会抢占 P？</a> </div>
                                            
                                            
                                            <div class="next">
                                                <span>Next >></span>
                                                <a href="https://www.lican.site/posts/go/go-map-access/">用 Go map 要注意这个细节，避免依赖他！</a> 
                                            </div>
                                            
                                        </nav>
                                    </div>
                                    
                                    

                                    
                                    
                                    

                                </div>
                            </article>
                        </div>
                    </div>
                </section>
                <aside class="sidebar sidebar-primary" id="sidebar-primary" role="complementary">
    <h1 class="screen-reader-text">Sidebar</h1>
    

    
    
    <section id="text-2" class="widget widget_text">
        <div class="textwidget">
            
            <div id="profile">
                <div id="profile_picture"><img src="https://www.lican.site/logo/logo.png"></div>
                <div id="profile_intro">
                    <p><span class="name">Lican</span></p>
                    <p class="intro">全栈开发者，爱好造轮子。</p>
                </div>
            </div>
            
            <p>
                <script type="text/javascript">
                    (function ($) {
                        $(document).ready(function () {
                            var menuPrimaryContainer = $('#menu-primary-container');
                            var profile = $('#text-2');
                            $('#toggle-navigation').click(function () {
                                if (menuPrimaryContainer.hasClass('open')) {
                                    profile.removeClass('open');
                                } else {
                                    profile.addClass('open');
                                }
                            });
                        });
                    })(jQuery);
                </script>
            </p>
        </div>
    </section>
    
    
    
    
    
    <section id="text-5" class="widget widget_text">
        <h2 class="widget-title">开源项目</h2>
        <div class="textwidget">
            <div id="projects" style="line-height: 22px;">
                
                <a href="https://github.com/idoubi/gonews"
                    target="_blank">gonews</a>: &nbsp;Daily news for golang<br>
                
                <a href="https://github.com/idoubi/sql2struct"
                    target="_blank">sql2struct</a>: &nbsp;Generate go struct according to SQL<br>
                
                <a href="https://github.com/idoubi/goz"
                    target="_blank">goz</a>: &nbsp;Request library used in golang<br>
                
        </div>
    </section>
    
    

    
    
    
    
    

    
    
    

    
    
    

    
    
    
    
</aside>
            </div>
        </div>

        <footer id="site-footer" class="site-footer" role="contentinfo">
    <div class="max-width">
    </div>
    <div class="footer">
        <div id="footercontent">
            © lican.vip All rights reserved<br/>
            Built with Hugo Theme <a href="https://github.com/idoubi/hugo-theme-period" target="_blank">Period</a>
        </div>
    </div>
</footer>

<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e8351b6d4626d5881d439ea1f6184baa";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
</script>
    
    
    </div>
    
</body>

</html>